package design;

import java.util.concurrent.ConcurrentHashMap;

public class ContainerSingleca {

	private ContainerSingleca(){}
	
	private static ConcurrentHashMap<String,Object> ioc = new ConcurrentHashMap<String,Object>();
	//双重检查方式，防止多线程下破坏单例模式。
	/*public static Object getInstance(String clazz){		
		if(!ioc.containsKey(clazz)){//此处判断，防止非第一次实例化，重复加锁，影响性能
			synchronized(ContainerSingleca.class){
				if(!ioc.containsKey(clazz)){
					Object o = null;
				try {
					o = Class.forName(clazz).newInstance();
				} catch (Exception e) {
					e.printStackTrace();
				}				
					ioc.put(clazz, o);
					return o;
				}
			}
		}
		return ioc.get(clazz);
	}*/
	private static String clazz;
	//静态内部类 实现
	private static class InnerClass{
		
		private static  Object INSTANCE =null;
		static{
			if(!ioc.containsKey(clazz)){
				try {
					INSTANCE = Class.forName(clazz).newInstance();
				} catch (Exception e) {
					e.printStackTrace();
				}				
				ioc.put(clazz, INSTANCE);
			}else{
				INSTANCE=ioc.get(clazz);
			}
		}
		 
	}
	public static Object getInstance(String className) throws Exception{
		clazz = className;
		return InnerClass.INSTANCE;
	}
}
